package guidePage;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;

import cn.smssdk.EventHandler;
import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import utils.KeyBoard;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.ToastUtils;
import utils.VariousUtils;

/**
 * Created by Administrator on 2017/3/1.
 */

@ContentView(R.layout.register)
public class RegisterPage extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.register_back)
    private TextView register_back;//取消
    @ViewInject(R.id.register_phone_edt)
    private EditText register_phone_edt;//手机号
    @ViewInject(R.id.register_pwd_edt)
    private EditText register_pwd_edt;//密码
    @ViewInject(R.id.register_verify_code_edt)
    private EditText register_verify_code_edt;//验证码
    @ViewInject(R.id.register_verify_code_btn)
    private Button register_verify_code_btn;//获取验证码按钮
    @ViewInject(R.id.register_back_login)
    private LinearLayout register_back_login;//返回登录界面
    @ViewInject(R.id.register_login_btn)
    private Button register_login_btn;//注册

    private String phoneNum = "";
    private String pwd = "";
    private String code = "";
    private boolean canGetCode = true;//验证码按钮是否可用
    private static final String TAG = "RegisterPage";

    private Thread codeTimer;
    private static final int SMS = 0;
    private static final int CODE_TIMER = 1;//验证码计时器倒计时
    private static final int RESULT_CODE = 1;

    private ErrorPageHandler myHandler = new ErrorPageHandler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(String.valueOf(msg.obj));
                        if (json != null) {
                            String error_code = json.getString("err_code");
                            if ("0".equals(error_code)) {
                                SharedPreferences.Editor edit = SPUtils.getSharedPreferences().edit();
                                String id = json.getString("id");
                                if(!TextUtils.isEmpty(id)) {
                                    ToastUtils.shortToast("注册成功");
                                    edit.putString(Constant.USER_ID,id );
                                    edit.commit();
                                    Intent i = new Intent(RegisterPage.this, CompletePersonalMessage.class);
                                    startActivityForResult(i, RESULT_CODE);//进入个人信息完善页
                                }else{

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case SMS:
                    //短信推送失败时
                    ToastUtils.shortToast((String) msg.obj);
                    break;
                case CODE_TIMER:
                    //验证码计时器倒计时
                    if (msg.arg1 == 0) {
                        canGetCode = true;
                        register_verify_code_btn.setText("获取验证码");
                        if (register_phone_edt.getText().toString().length() >= 11) {
                            register_verify_code_btn.setClickable(true);
                            register_verify_code_btn.setBackgroundColor(RegisterPage.this.getResources().getColor(R.color.common_color));
                        }
                        codeTimer.interrupt();
                    } else {
                        canGetCode = false;
                        register_verify_code_btn.setText(msg.arg1 + "秒");
                        register_verify_code_btn.setClickable(false);
                        register_verify_code_btn.setBackgroundColor(RegisterPage.this.getResources().getColor(R.color.unfocusable));
                    }
                    break;
                default:
                    break;
            }
        }
    };


    //短信监听
    private EventHandler eh = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {

            if (result == cn.smssdk.SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == cn.smssdk.SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                } else if (event == cn.smssdk.SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                } else if (event == cn.smssdk.SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else {
                Throwable throwable = (Throwable) data;
                String message = throwable.getMessage();
                MyLogUtils.e(TAG, message);
                try {
                    JSONObject json = new JSONObject(message);
                    String detail = json.getString("detail");
                    Message msg = new Message();
                    msg.obj = detail;
                    msg.what = SMS;
                    myHandler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        register_phone_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (canGetCode) {
                    int color;
                    boolean clickable;
                    if (isMobileNumber(register_phone_edt.getText().toString())) {
                        color = RegisterPage.this.getResources().getColor(R.color.common_color);
                        clickable = true;
                    } else {
                        color = RegisterPage.this.getResources().getColor(R.color.unfocusable);
                        clickable = false;
                    }
                    register_verify_code_btn.setClickable(clickable);
                    register_verify_code_btn.setBackgroundColor(color);
                }
                listenInputState();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        register_pwd_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                listenInputState();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        register_verify_code_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                listenInputState();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void getVerifyCode(String phoneNum) {
        codeTimer = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 60; i >= 0; i--) {
                        Message msg = new Message();
                        msg.what = CODE_TIMER;
                        msg.arg1 = i;
                        myHandler.sendMessage(msg);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        codeTimer.start();
        cn.smssdk.SMSSDK.getVerificationCode(Constant.CHINA_CODE, phoneNum);
        cn.smssdk.SMSSDK.registerEventHandler(eh);
    }

    private void initView() {
        register_back.setOnClickListener(this);
        register_back_login.setOnClickListener(this);
        register_verify_code_btn.setOnClickListener(this);
        register_login_btn.setOnClickListener(this);
    }

    private void listenInputState() {
        phoneNum = register_phone_edt.getText().toString();
        pwd = register_pwd_edt.getText().toString();
        code = register_verify_code_edt.getText().toString();
        if ((!(TextUtils.isEmpty(pwd) || TextUtils.isEmpty(code))) && isMobileNumber(phoneNum)) {
            //所有输入都不为空时
            register_login_btn.setBackgroundResource(R.drawable.shape_login_focusable);
            register_login_btn.setClickable(true);
        } else {
            register_login_btn.setBackgroundResource(R.drawable.shape_login_unfocusable);
            register_login_btn.setClickable(false);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_back:
                RegisterPage.this.finish();
                break;
            case R.id.register_login_btn://注册登录
                code = register_verify_code_edt.getText().toString().trim();
                pwd = register_pwd_edt.getText().toString().trim();
                if (phoneNum.length() >= 11) {
                    if (!TextUtils.isEmpty(pwd)) {
                        if (code.length() >= 4) {
                            register(phoneNum, pwd, code);
                        } else {
                            ToastUtils.shortToast("验证码格式错误");
                        }
                    } else {
                        ToastUtils.shortToast("密码不能为空");
                    }
                } else {
                    ToastUtils.shortToast("手机号格式错误");
                }

                break;
            case R.id.register_verify_code_btn:
                //获取验证码
                getVerifyCode(phoneNum);
                break;
            default:
                break;
        }
    }

    //显示键盘
    private void showKeyBoard() {
        KeyBoard.showKeyBoard();
    }

    /**
     * 验证手机格式
     */
    private static boolean isMobileNumber(String mobiles) {
        if (mobiles.length() < 11) return false;
        else return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cn.smssdk.SMSSDK.unregisterEventHandler(eh);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        RegisterPage.this.setResult(RESULT_CODE);
        RegisterPage.this.finish();
    }



    private void register(String phone, String pwd, String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("tel", phone);
        hashMap.put("pwd", pwd);
        hashMap.put("code", code);
        String clientid = SPUtils.getSharedPreferences().getString(Constant.CLIENTID,"");
        if(!TextUtils.isEmpty(clientid)){
            String phoneType = android.os.Build.MODEL; // 手机型号
            String androidType = Build.VERSION.RELEASE; // 当前安卓系统版本
            hashMap.put("ver", VariousUtils.getVersion());
            hashMap.put("os", "android");
            hashMap.put("deviceinfo", phoneType + ":" + androidType);
            hashMap.put("clientid", clientid);
        }
        new InterNetController(RegisterPage.this, Constant.REGESITER, myHandler, hashMap, 0);


        //测试用的，可以删了
//        RequestParams requestParams = new RequestParams("");
//        String random = SignatureUtil.GetRandom();
//        final String timeStamp = SignatureUtil.GetTimeStamp();
//        requestParams.addParameter("rdStr", random);
//        requestParams.addParameter("timestamp", timeStamp);
//        if (hashMap != null) {
//            if (hashMap.size() != 0) {
//                Set set = hashMap.keySet();
//                Iterator iter = set.iterator();//遍历插入
//                while (iter.hasNext()) {
//                    String key = (String) iter.next();
//                    requestParams.addParameter(key, hashMap.get(key));
//                    hashMap.put(key, String.valueOf(hashMap.get(key)));
//                }
//            }
//        }
//        hashMap.put("rdStr", random);
//        hashMap.put("timestamp", timeStamp);
//        String id = SPUtils.getSharedPreferences().getString(Constant.USER_ID, "");
//        if (!TextUtils.isEmpty(id)) {
//            requestParams.addParameter("ac_id", id);
//            hashMap.put("ac_id", id);
//        }
//        requestParams.addParameter("sign", SignatureUtil.getSignature(hashMap));
    }

}
